from django.shortcuts import render
from django.template import RequestContext, loader
from django.http import HttpResponse, JsonResponse
from . import sms_demo
import sys
from .models import (User, Post, Author,
                     Floor, DormSpecs, Dorm, DormEquipRela, Students,SchoolLocation,
                     CourseSlave, CourseMaster)
import json
import os
from django.db.models import Count
from django.core.paginator import Paginator
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
import xlwt
from io import BytesIO

from django.core import serializers
# Create your views here.


def login(request):
    template = loader.get_template('login.html')
    return HttpResponse(template.render())


def sms_send(request):
    phone_number = request.POST['phone']
    request_module = request
    try:
        sms_demo.Sample.main(sys.argv[1:], phone_number, request_module)
        return JsonResponse({'status': 1, 'msg': '返回成功', 'data': []})
    except Exception as e:
        return JsonResponse({'status': 2, 'msg': str(e), 'data': []})


def sms_check(request):
    """
    手机号登录验证
    :param request:
    :return:
    """
    phone_number = request.POST['phone']
    res_code = request.POST['code']
    code = request.session.get(str(phone_number))
    try:
        if code:
            if str(res_code) == str(code):
                # 验证码验证过了，将用户的信息存储到session
                    is_exist = User.objects.filter(phone=phone_number).get()
                    if is_exist:
                        # 写入session
                        request.session['user_info'] = json.dumps({
                            'username': is_exist.username,
                            'id': is_exist.id,
                            'phone': is_exist.phone,
                            'job_number': is_exist.job_number
                        })
                        return JsonResponse({'status': 1, 'msg': '验证成功', 'data': []})
                    else:
                        return JsonResponse({'status': 4, 'msg': '验证失败，请联系后台管理员添加用户', 'data': []})

            else:
                return JsonResponse({'status': 3, 'msg': '验证码不一致', 'data': []})
        else:
            return JsonResponse({'status': 2, 'msg': '验证码失效', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'status': 4, 'msg': '验证失败，请联系后台管理员添加用户', 'data': []})


def login_check(request):
    """
    账号密码登录，接口返回
    :param request:
    :return:
    """
    username = request.POST['phone']
    password = request.POST['password']
    # return JsonResponse({'status': 1, 'msg': '登录成功', 'data': {}})
    # 验证密码，通过了将用户的信息存储到session
    try:
        is_exist = User.objects.filter(phone=username).get()
        if is_exist:
            if password == is_exist.password:
                # 写入session
                request.session['user_info'] = json.dumps({
                    'username': is_exist.username,
                    'id': is_exist.id,
                    'phone': is_exist.phone,
                    'job_number': is_exist.job_number
                })

                return JsonResponse({'status': 1, 'msg': '登录成功', 'data': {}})
            else:
                return JsonResponse({'status': 2, 'msg': '密码错误', 'data': {}})
    except Exception as e:
        print(e)
        return JsonResponse({'status': 4, 'msg': '验证失败，请联系后台管理员添加用户', 'data': []})


def index(request):
    # 根据当前登录的用户的角色，把对应的角色权限列出来
    user_id = json.loads(request.session.get('user_info'))["id"]
    user_obj = User.objects.get(id=user_id)
    post_obj = Post.objects.get(id=user_obj.post_id_id).author_set.all()
    # print(post_obj)
    author_ids = [item.id for item in post_obj]
    author_list = Author.objects.filter(id__in=author_ids).filter(is_delete=1)
    print(author_list)
    data = {'menu_list': author_list}
    return render(request, 'index.html', data)


def main(request):
    template = loader.get_template('main.html')
    return HttpResponse(template.render())


def postList(request):
    template = loader.get_template('post_list.html')
    return HttpResponse(template.render())


def postListApi(request):
    """
    岗位列表接口
    :param request: 当前页，每页显示多少条
    :return: json格式的岗位列表
    """
    current_page = request.GET['page']
    limit = request.GET['limit']
    results = Post.objects.values('id', 'post_name', 'description', 'status').filter(is_delete=1).annotate(Count('user')).order_by('-id')
    result = [{'id': item['id'], 'post_name': item['post_name'],
               'description': item['description'], 'user__count': item['user__count'],
               'status': item['status']
               } for item in results]

    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "data": res})


def postAdd(request):
    template = loader.get_template('post_add.html')
    return HttpResponse(template.render())


def postAddApi(request):
    try:
        postObj = Post()
        postObj.post_name = request.POST['post_name']
        postObj.description = request.POST['description']
        postObj.save()
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def changePostAuthApi(request):
    id = request.POST['id']
    # 先查询之前的状态，改相反的状态
    res = Post.objects.filter(pk=id).update(status=2)
    if res:
        return JsonResponse({'code': 0, 'msg': '更改成功', 'data': []})
    else:
        return JsonResponse({'code': 1, 'msg': '更改失败', 'data': []})


def changePostDelApi(request):
    id = request.POST['id']
    res = Post.objects.filter(pk=id).update(is_delete=2)
    if res:
        return JsonResponse({'code': 0, 'msg': '删除成功', 'data': []})
    else:
        return JsonResponse({'code': 1, 'msg': '删除失败', 'data': []})


def authorList(request):
    # print(request.GET)
    uid = request.GET['user_id']
    authorL_list = Author.objects.filter(is_delete=1).all()
    result = [{'id': item.id, 'author_name': item.author_name,
               'author_name_en': item.author_name_en, 'url': item.url,
               'pid': item.pid
               } for item in authorL_list]

    # 把这个角色的所有的权限都拿出来
    au_list = Author.objects.filter(post_id=uid)
    # print(list(au_list))
    # 把id取出来
    auid_list = [item.id for item in au_list]
    # print(auid_list)

    data = {'result': result, 'user_id': uid,'auid_list': auid_list}
    return render(request, 'author_list.html', data)


def authorSave(request):
    author_list = dict(request.POST)
    try:
        Post.objects.get(id=author_list['data_list[0][]'][0]).author_set.clear()

        for key, value in author_list.items():
            Post.objects.get(id=value[0]).author_set.add(Author.objects.get(id=value[1]))

        return JsonResponse({'status': 0, 'msg': '保存成功', 'data': []})
    except ObjectDoesNotExist:
        for key, value in author_list.items():
            Post.objects.get(id=value[0]).author_set.add(Author.objects.get(id=value[1]))
        return JsonResponse({'status': 0, 'msg': '保存成功', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'status': 1, 'msg': '保存失败', 'data': []})


def userList(request):
    return render(request, 'user_list.html', {})


def userListApi(request):
    status = request.GET.get('status', '')
    source = request.GET.get('source', '')
    job_number = request.GET.get('job_number', '')

    current_page = request.GET['page']
    limit = request.GET['limit']

    results = User.objects.values('id', 'job_number', 'username', 'gender', 'phone', 'status',
                                  'office_date')

    if status:
        results = results.filter(status=status)
    if source:
        results = results.filter(source=source)
    if job_number:
        results = results.filter(job_number__icontains=job_number)

    results = results.order_by('-id')

    result = [{'id': item['id'], 'job_number': item['job_number'],
               'username': item['username'], 'gender': item['gender'],
               'phone': item['phone'],
               'status': item['status'],
               'office_date': item['office_date']
               } for item in results]   # 查询出来的result查询结果集，在前端没办法直接用

    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})


def uploadFile(request):
    # file_source = request.FILES
    # print(file_source)

    file = request.FILES['file']
    print("上传的文件名是：", file.name)
    filename = os.path.join(settings.MEDIA_ROOT, file.name)
    # 在这里批量插入数据库
    objects = []
    with open(filename, "wb") as f:
        data = file.file.read()
        f.write(data)

    # 本地文件的路径
    # print(filename)
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        # 掐头去尾
        lines.pop(0)
        lines.pop(len(lines)-1)

        for line in lines:
            temp = line.split(',')
            sex = 1
            if temp[3].strip() == '女':
                sex = 2

            status = 1
            if temp[5].strip() == '异常':
                status = 2

            objects.append(User(job_number=temp[1].strip("\""), username=temp[2].strip("\""), password='123456',
                                gender=sex, phone=temp[4].strip("\""),
                                source='内聘', status=status, office_date=temp[6].strip("\",\n"), manage_area='1,2,3,4,5',
                                id_num='123456789123456789', off_office_date='2024-03-29', post_id_id=9))

    User.objects.bulk_create(objects)

    return JsonResponse({'code': 0, 'msg': '上传成功', 'data': {}})


def exportToExcel(request):
    # 创建一个workbook对象，相当于创建了一个Excel文件
    workbook = xlwt.Workbook(encoding='utf-8')
    # 添加一个sheet页，命名为'数据'
    worksheet = workbook.add_sheet('数据', cell_overwrite_ok=True)

    titles = ['编号', '工号', '姓名', '性别', '手机号', '状态', '日期']
    for index, header in enumerate(titles):
        worksheet.write(0, index, label=header)

    # 假设我们要导出一些用户数据
    # 从数据库或其他地方获取数据

    results = User.objects.values('id', 'job_number', 'username', 'gender', 'phone', 'status',
                                  'office_date')

    users = results.order_by('id')

    result = [{'id': item['id'], 'job_number': item['job_number'],
               'username': item['username'], 'gender': item['gender'],
               'phone': item['phone'],
               'status': item['status'],
               'office_date': item['office_date']
               } for item in results]  # 查询出来的result查询结果集，在前端没办法直接用

    # 将数据写入到worksheet中
    for index, user in enumerate(users):
        worksheet.write(index + 1, 0, user['id'])
        worksheet.write(index + 1, 1, user['job_number'])
        worksheet.write(index + 1, 2, user['username'])
        worksheet.write(index + 1, 3, user['gender'])
        worksheet.write(index + 1, 4, user['phone'])
        worksheet.write(index + 1, 5, user['status'])
        worksheet.write(index + 1, 6, user['office_date'])

    # 创建HttpResponse对象返回Excel文件
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="用户数据.xls"'

    workbook.save(response)
    return response


def userAdd(request):
    post_list = Post.objects.filter(status=1).filter(is_delete=1).all()
    data = {'post_list': post_list}
    return render(request, 'user_add.html', data)


def userAddApi(request):
    try:
        userObj = User()
        userObj.job_number = request.POST['job_number']
        userObj.password = request.POST['password']
        userObj.username = request.POST['username']
        userObj.gender = request.POST['gender']
        userObj.post_id_id = request.POST['post']
        userObj.source = request.POST['source']
        userObj.phone = request.POST['phone']
        userObj.id_num = request.POST['id_num']
        userObj.office_date = request.POST['office_date']
        userObj.off_office_date = request.POST['off_office_date']
        status = request.POST['status']
        userObj.status = 1 if status == 'on' else 2
        userObj.save()
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def floorManage(request):
    return render(request, 'floor_manage.html', {})


def floorListApi(request):
    current_page = request.GET['page']
    limit = request.GET['limit']

    results = Floor.objects.values('id', 'floor_name', 'description', 'is_delete')

    results = results.filter(is_delete=1).order_by('-id')

    result = [{'id': item['id'], 'floor_name': item['floor_name'],
               'description': item['description'], 'is_delete': item['is_delete']} for item in results]   # 查询出来的result查询结果集，在前端没办法直接用

    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})


def dormSpecs(request):
    return render(request, 'dorm_specs.html', {})


def dormSpecsApi(request):
    current_page = request.GET['page']
    limit = request.GET['limit']

    results = DormSpecs.objects.values('id', 'scale', 'num', 'description', 'is_delete')

    results = results.filter(is_delete=1).order_by('-id')

    result = [{'id': item['id'], 'scale': str(item['scale']) + '人间', 'num': item['num'],
               'description': item['description'], 'is_delete': item['is_delete']} for item in results]   # 查询出来的result查询结果集，在前端没办法直接用

    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})


def dormManage(request):
    floor_data = Floor.objects.filter(is_delete=1).values('id', 'floor_name')
    dorm_data = DormSpecs.objects.filter(is_delete=1).order_by('scale').values('id', 'scale')
    return render(request, 'dorm_manage.html', {'floor_data': floor_data, 'dorm_data': dorm_data})


def dormManageApi(request):
    current_page = request.GET['page']
    limit = request.GET['limit']

    floor_id = request.GET.get('floor_id', '')
    # scale = request.GET['floor_id']

    results = Dorm.objects.order_by('-id').values()

    data = []

    for x in results:
        # 查询宿舍的列表
        dorm_obj = Dorm.objects.get(id=x['id'])
        # 根据宿舍floor_id 查找楼层信息
        floor_obj = Floor.objects.get(id=dorm_obj.floor_id)
        # 根据宿舍spec_id 查找规格信息
        spec_obj = DormSpecs.objects.get(id=dorm_obj.spec_id)

        temp = {'dorm_name': dorm_obj.dorm_name, 'floor_name': floor_obj.floor_name, 'floor_id': floor_obj.id,
                     'scale': spec_obj.scale, 'num': spec_obj.num, 'id': dorm_obj.id,
                     'equip1_num': 0,
                     'equip2_num': 0,
                     'equip3_num': 0,
                     'equip4_num': 0,
                     'equip5_num': 0,
                     'equip6_num': 0,
                     'equip7_num': 0,
                     }

        # 房间里的家具查询出来
        equip_obj = DormEquipRela.objects.filter(dorm_id=dorm_obj.id).values()

        if equip_obj:
            temp['equip1_num'] = equip_obj[0]['num']
            temp['equip2_num'] = equip_obj[1]['num']
            temp['equip3_num'] = equip_obj[2]['num']
            temp['equip4_num'] = equip_obj[3]['num']
            temp['equip5_num'] = equip_obj[4]['num']
            temp['equip6_num'] = equip_obj[5]['num']
            temp['equip7_num'] = equip_obj[6]['num']

        data.append(temp)

    filtered_dict = data
    if floor_id:
        filtered_dict = [temp for temp in data if temp['floor_id'] == int(floor_id)]

    p = Paginator(filtered_dict, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})


def studentManage(request):
    return render(request, 'student_manage.html', {})


def studentManageApi(request):
    current_page = request.GET['page']
    limit = request.GET['limit']

    # results = Students.objects.select_related('dorm_id').all()
    results = Students.objects.values()
    results.filter(status=1)
    result = [{'stu_number': item['stu_number'],
               'username': item['username'],
               'id': item['id'],
               'gender': item['gender'],
               'grade': item['grade'],
               'class_name': item['class_name'],
               'stu_phone': item['stu_phone'],
               'par_phone': item['par_phone'],
               'is_distribution': item['is_distribution'],
               'floor_name': Students.objects.select_related('floor_id').first().floor_id.floor_name,
               'dorm_name': Students.objects.select_related('dorm_id').first().dorm_id.dorm_name
               } for item in results]  # 查询出来的result查询结果集，在前端没办法直接用
    # result = []
    print(result)
    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})

def locationManage(request):
    location_info = SchoolLocation.objects.all().last()
    data = {'location_info': location_info}
    return render(request, 'location_manage.html', data)


def locationApi(request):
    try:
        localObj = SchoolLocation()
        localObj.lat = request.POST['location'].split(',')[0]
        localObj.long = request.POST['location'].split(',')[1]
        localObj.save()
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def majorManage(request):
    return render(request, 'major_manager.html', {})


def majorSlave(request):
    mater_id = request.GET['mater_id']
    print(mater_id)
    print('-------------')
    # 查询课程的从表，将对应专业的所有课程显示出来
    res = CourseSlave.objects.filter(master_id=mater_id).all()
    result = []
    if res:
        result = list(res.values())

    temp = {'星期一': {}, '星期二': {}, '星期三': {}, '星期四': {}, '星期五': {}}

    for x in result:
        for y, z in temp.items():
            if x['name'] == y:
                temp[y] = x

    print(temp)

    return render(request, 'major_slave.html', {'mater_id': mater_id, 'res': temp})


def majorSlaveApi(request):
    try:
        slaveObj = CourseSlave()
        slaveObj.name = request.POST['name']
        slaveObj.first_class = request.POST['first_class']
        slaveObj.second_class = request.POST['second_class']
        slaveObj.third_class = request.POST['third_class']
        slaveObj.fourth_class = request.POST['fourth_class']
        slaveObj.fifth_class = request.POST['fifth_class']
        slaveObj.sixth_class = request.POST['sixth_class']
        slaveObj.master_id = int(request.POST['master_id'])
        slaveObj.save()
        # 从表周一到周五都生成了，但是主表什么时候存储
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def yearManage(request):
    return render(request, 'year_manager.html', {})


def yearManageApi(request):
    current_page = request.GET['page']
    limit = request.GET['limit']
    results = CourseMaster.objects.values()
    results.filter(is_delete=1).order_by('major_id')
    result = [{'major_id': item['major_id'],
               'name': item['name'],
               'id': item['id'],
               'year': item['year'],
               'semester': item['semester'],
               } for item in results]  # 查询出来的result查询结果集，在前端没办法直接用
    # result = []
    print(result)
    p = Paginator(result, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    res = res.object_list
    return JsonResponse({"code": 0, "msg": "", "count": counter, "current_page": current_page, "data": res})


def majorTree(request):
    major_id = request.GET['major']
    return render(request, 'major_tree.html', {'major_id':major_id})

def majorTreeApi(request):
    major_id = request.POST['major_id']
    results = CourseMaster.objects.filter(is_delete=1,major_id=major_id).values('major_id')
    data = list(results.values())
    temp_dict = {
        '1': '24电商综合一班',
        '2': '22大数据软件开发',
        '3': '23网络技术',
        '4': '21幼师',
    }
    # 创建一个空字典
    result_dict = {}
    # 定义一个列表 专业
    my_list = [int(major_id)]
    # 使用 for 循环将列表中的元素添加到字典中
    for i in my_list:
        result_dict.update({i: {'id': i, 'title': '', 'children': []}})


    for a, b in result_dict.items():
        for x in data:
            if int(x['major_id']) == a:
                result_dict[a]['id'] = a
                result_dict[a]['title'] = temp_dict[str(a)]
                temp = {'id': x['id'], 'title': x['name'], 'children': []}
                result_dict[a]['children'].append(temp)

    # 输出字典
    print(result_dict)
    new_list = []
    for x, y in result_dict.items():
        new_list.append(y)

    return JsonResponse({'code': 0, 'msg': '请求成功', 'data': new_list})